package unimelb.distSystems.project2;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

import javax.imageio.ImageIO;

import unimelb.distSystems.communications.CORBA.ServiceAccount;

/*
 * Player class is an entity type for racing session 
 */
public class Player implements Serializable {
	private long player_id;
	private String driver_name;
	private String username;
	private String md5_password;
	private byte[] avatar_bytes;
	//private ???? statistics
	
	/*
	 * Constructor
	 */
	public Player(long player_id,String driver_name,String username,String md5_password,BufferedImage avatar){
		this.player_id=player_id;
		this.driver_name=driver_name;
		this.username=username;
		this.md5_password=md5_password;
		setAvatar(avatar);
	}
	
	public Player(ServiceAccount account) {
        this.player_id = account.userID;
        this.username = account.username;
        this.md5_password = account.password;
        this.driver_name = account.driverName;
        this.avatar_bytes = account.avatar;
	}
	
	/*
	 * Get unique ID of player
	 * Input: Nothing
	 * Output: long value of player ID
	 */
	public long getPlayerID()
	{
		return player_id;
	}
	
	public void setPlayer_id(long player_id)
    {
        this.player_id = player_id;
    }
	
	/*
	 * Get driver name of player
	 * Input: Nothing
	 * Output: String driver name
	 */
	public String getDriverName()
	{
		return driver_name;
	}
	
	/*
	 * Get username of player
	 * Input: Nothing
	 * Output: String username
	 */
	public String getUsername()
	{
		return username;
	}
	
	/*
	 * Get encrypted password of player
	 * Input: Nothing
	 * Output: String encrypted password
	 */
	public String getMD5Password()
	{
		return md5_password;
	}
	
	/*
	 * Get avatar picture of player
	 * Input: Nothing
	 * Output: Reference of BufferedImage avatar
	 */
	public BufferedImage getAvatar()
	{
		if(avatar_bytes==null)
			return null;
		
		InputStream in = new ByteArrayInputStream(avatar_bytes);
		BufferedImage b_img=null;
		try {
			b_img = ImageIO.read(in);
		} catch (IOException e) {}
		return b_img;
	}
	
	/*
	 * Store avatar picture of player as byte array for serializable
	 * Input: Reference of BufferedImage avatar
	 * Output: Nothing
	 */
	public void setAvatar(BufferedImage avatar)
	{
		if(avatar==null)
		{
			avatar_bytes = null;
			return;
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			ImageIO.write(avatar, "jpeg", baos);
		} catch (IOException e) {}
		avatar_bytes = baos.toByteArray();
	}
	
	public byte[] getAvatar_bytes() {
        return avatar_bytes;
    }
}
